/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Input, InputNumber, Modal, notification, Popconfirm, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormField, FormLayout, ModalFooter, ModalView} from "antd-extra";
import ViewTitle from "../../../components/ViewTitle";

import styles from "../../index.less";
import notify from "../../../components/NotificationExtra";
import UploadPic from "../../../components/UploadPic";
import ModalSelectMaterial from "./ModalSelectMaterial";
import ModalSelectStoreLots from "./ModalSelectStoreLots";
import MaterialElement from "../../finance/modal/MaterialElement";

moment.locale('zh-cn');
const table = 'SalesOrder';
@Form.create()
@connect(({
            user,
            global,
            sales,
            material,
            store
          }) => ({...user, ...material, ...sales, ...global, ...store}))
export default class ModalCreateOrEditProd extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    const {spLotId = 'SPD' + moment().format('YYYYMMDDHHmmss'), amount = 0, laborFee = 0} = record;
    this.state = {...record, spLotId, _laborFee: laborFee};
  }

  componentDidMount() {
    const {numberValue} = this.state;
    console.log('numberValue', numberValue);
    if (numberValue) {
      this.props.dispatch({
        type: 'sales/findNumberTxt',
        payload: {txt: numberValue}
      });
    }
  }

  materialBaseCols() {
    return [
      {
        title: '原料', key: 'code', dataIndex: "code", render: (value, record) => {
          const {code, name} = record;
          return <MaterialElement code={code} name={name}></MaterialElement>;
        }
      },
      {title: '原料形态', key: 'subcategory', dataIndex: "subcategory"},
      {title: '原料类型', key: 'type', dataIndex: "type"},
      {title: '原料编号', key: 'number', dataIndex: "number"},
      {title: '原料含量%', key: 'materialContent', dataIndex: "materialContent"}
    ];
  }


  lotBaseCols() {
    return [
      {
        title: '原料', key: 'code', dataIndex: "code", render: (value, record) => {
          const {code, name} = record;
          return <MaterialElement code={code} name={name}></MaterialElement>;
        }
      },
      {title: '原料类型', key: 'type', dataIndex: "type"},
      {title: '原料编号', key: 'number', dataIndex: "number"},
      {title: '原料形态', key: 'subcategory', dataIndex: "subcategory"},
      {title: '供应商', key: 'vendor', dataIndex: "vendor"},
      {title: '原料含量%', key: 'materialContent', dataIndex: "materialContent"},
      {title: '原料数量', key: 'materialCount', dataIndex: "materialCount"},
      {title: '原料单价', key: 'price', dataIndex: "price"},
      {
        title: '成本', key: 'materialCost', dataIndex: "materialCost", render: (value, record) => {
          const {price = 0, materialCount = 0} = record;
          return <div>{price * materialCount}</div>;
        }
      },
      {title: '采购运费成本', key: 'procureShippingFee', dataIndex: "procureShippingFee"},
      {title: '入库数量', key: 'inboundCount', dataIndex: "inboundCount"},
      {
        title: '入库时间', key: 'inboundDate', dataIndex: "inboundDate", render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      }
    ];
  }

  /**
   * 原料信息
   * @returns {[{title: string, key: string, dataIndex: string, render: function(*, *): *},{title: string, key: string, dataIndex: string},{title: string, key: string, dataIndex: string},{title: string, key: string, dataIndex: string},{title: string, key: string, dataIndex: string}]}
   */
  materialTableCol() {
    const {form} = this.props;
    const {projectType} = this.state;
    const cols = this.materialBaseCols();
    if (projectType === '出租') _.remove(cols, item => {
      return item.key === 'materialContent';
    });
    cols.push({
      title: '操作', key: 'opt', dataIndex: "opt", render: (value, record) => {
        return <span>
                    {<Popconfirm
                      title="确认删除"
                      onConfirm={() => {
                        const {materials} = this.state;
                        _.remove(materials, item => {
                          return item.usedLotId === record.usedLotId;
                        });
                        const temp = this.state;
                        temp.materials = materials;
                        this.setState({...temp});
                      }}
                      okText="是"
                      cancelText="否"
                    >
                      <a style={{marginRight: '6px'}}>删除</a>
                    </Popconfirm>}
          <a style={{marginRight: '6px'}}
             onClick={() => {
               const {count = 0} = form.getFieldsValue();
               if (count === 0) {
                 notify({type: 'warning', message: "请输入数量"});
                 return;
               }
               const {materialContent} = record;
               const {materialLots = [], projectType} = this.state;
               ModalView.open(ModalSelectStoreLots, {
                 title: '选择库存批次',
                 width: '1580px',
                 maskClosable: false
               }, {
                 count, materialContent, isPkg: projectType === '出租',
                 record,
                 isEdit: true,
                 callback: (data) => {
                   data.usedLotId = 'UID' + moment().valueOf();
                   const {materialCount = 0, inboundCount = 0, procureShippingFee = 0} = data;
                   data.procureShippingFee = procureShippingFee * (materialCount / inboundCount);
                   materialLots.push(data);
                   const temp = this.state;
                   temp.materialLots = materialLots;
                   this.setState({...temp});
                 }
               });
             }}
          >选择库存批次</a>
            </span>;
      }
    });
    return cols;
  }

  /**
   * 原料库存批次信息
   * @returns {*}
   */
  materialLotTableCol() {
    const cols = this.lotBaseCols();
    cols.push({
      title: '操作', key: 'opt', dataIndex: "opt", fixed: 'right', render: (value, record) => {
        return <span>

            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                const {materialLots} = this.state;
                _.remove(materialLots, item => {
                  return item.usedLotId === record.usedLotId;
                });
                const temp = this.state;
                temp.materialLots = materialLots;
                this.setState({...temp});
              }}
              okText="是"
              cancelText="否"
            >
              <a style={{marginRight: '6px'}}>删除</a>
            </Popconfirm>}
            </span>;
      }
    });
    return cols;
  }

  pkgCols() {
    const cols = this.materialBaseCols();
    _.remove(cols, item => {
      return item.key === 'materialContent';
    });
    cols.push({
      title: '操作', key: 'opt', dataIndex: "opt", render: (value, record) => {
        return <span>
          {<Popconfirm
            title="确认删除"
            onConfirm={() => {
              const {pkgMaterials} = this.state;
              _.remove(pkgMaterials, item => {
                return item.usedLotId === record.usedLotId;
              });
              const temp = this.state;
              temp.pkgMaterials = pkgMaterials;
              this.setState({...temp});
            }}
            okText="是"
            cancelText="否"
          >
            <a style={{marginRight: '6px'}}>删除</a>
          </Popconfirm>}
          {<a style={{marginRight: '6px'}}
              onClick={() => {
                const {pkgLots = []} = this.state;
                ModalView.open(ModalSelectStoreLots, {
                  title: '选择库存批次',
                  width: '1580px',
                  maskClosable: false
                }, {
                  record,
                  isPkg: true,
                  callback: (data) => {
                    const {materialCount = 0, inboundCount = 0, procureShippingFee = 0} = data;
                    data.procureShippingFee = procureShippingFee * (materialCount / inboundCount);
                    data.usedLotId = 'UID' + moment().valueOf();
                    pkgLots.push(data);
                    const temp = this.state;
                    temp.pkgLots = pkgLots;
                    this.setState({...temp});
                  }
                });
              }}
          >选择库存批次</a>}
            </span>;
      }
    });
    return cols;

  }

  pkgLotCols() {
    const cols = this.lotBaseCols();
    _.remove(cols, item => {
      return item.key === 'materialContent';
    });
    cols.push({
      title: '操作', key: 'opt', dataIndex: "opt", render: (value, record) => {
        return <span>
          {<Popconfirm
            title="确认删除"
            onConfirm={() => {
              const {pkgLots} = this.state;
              _.remove(pkgLots, item => {
                return item.usedLotId === record.usedLotId;
              });
              const temp = this.state;
              temp.pkgLots = pkgLots;
              this.setState({...temp});
            }}
            okText="是"
            cancelText="否"
          >
            <a style={{marginRight: '6px'}}>删除</a>
          </Popconfirm>}
            </span>;
      }
    });
    return cols;

  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              const {materials = [], pkgMaterials = [], pkgLots = [], materialLots = [], fileList = []} = this.state;
              if (fileList.length === 0) {
                notify({type: 'error', message: "请上传标签样式"});
                return;
              }
              values.materials = materials;
              values.pkgMaterials = pkgMaterials;
              values.materialLots = materialLots;
              values.pkgLots = pkgLots;
              values.fileList = fileList;
              callback(values);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  picHandleCancel = () => this.setState({previewVisible: false});


  render() {
    const {form, cols = 3, numberTxt = {}} = this.props;
    const {numberValue=""} = this.state;
    console.log('numberTxt', numberTxt);
    const model = this.props[`${table}Model`];
    if (!model) return <div></div>;

    const {
      prodName,
      prodCode,
      price = 0,
      laborFee = 0,
      taxDeductionPointForLaborCosts = 0,
      deliverWay,
      count = 0, unit,
      label,
      pkg, projectType,
      memo, pkgFee = 0,
      pkgMaterials = [], laborFeeRatio = 0,
      previewVisible, previewImage, fileList = [], materials = [], pkgLots = [], materialLots = []
    } = this.state;
    const laborFeeTax = laborFee * (laborFeeRatio / 100);
    const fastLaborFee = laborFee - laborFeeTax;
    let materialCost = 0, shippingFee = 0;

    _.map(materialLots, async material => {
      const {materialCount = 0, price = 0, procureShippingFee = 0} = material;
      materialCost += materialCount * price;
      shippingFee += procureShippingFee;
    });

    const amount = price * count;
    let warnStr = amount !== 0 && amount !== this.state.amount && laborFee === this.state._laborFee ? '金额发生变化 ，请调整【项目奖励】等其它数据' : undefined;
    const subTitle = numberTxt ? `编号：${numberValue} 已到：${numberTxt.number}` : undefined;
    console.log('xxxx', subTitle);
    return (
      <div>
        <ViewTitle
          title={'商品信息'}
          subTitle={subTitle}
        >
        </ViewTitle>
        <FormLayout form={form} cols={cols}>
          <FormField
            label={'品名'}
            name={'prodName'}
            required={true}
            initialValue={prodName}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'编号'}
            name={'prodCode'}
            required={true}
            initialValue={prodCode}
          >
            <Input onChange={e => {
              console.log('xxxx', e.target.value);
              this.state.numberValue = e.target.value;
              this.componentDidMount();
            }} style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'数量'}
            name={'count'}
            required={true}
            initialValue={count}
          >
            <InputNumber onChange={v => {
              this.state.count = v;
              this.componentDidMount();
            }} disabled={materialLots.length > 0} style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'单位'}
            name={'unit'}
            initialValue={unit}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'单价'}
            name={'price'}
            required={true}
            initialValue={price}
          >
            <InputNumber onChange={(v) => {
              this.state.price = v;
              this.componentDidMount();
              // const values = form.getFieldsValue();
              // const {price = 0, count = 0} = values;
              // const amount = price * count;
              // form.setFieldsValue({amount});
              // this.state.price = v;
              // this.componentDidMount();
            }} style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'金额'}
            name={'amount'}
            initialValue={amount}
          >
            <InputNumber disabled style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'标签'}
            name={'label'} initialValue={label}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装'}
            name={'pkg'} initialValue={pkg}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装费用'}
            name={'pkgFee'} initialValue={pkgFee}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>

          <FormField
            label={'劳务扣税金额'}
            name={'taxDeductionPointForLaborCosts'}
            initialValue={taxDeductionPointForLaborCosts}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'发货方式'}
            name={'deliverWay'} initialValue={deliverWay}
          >
            <Select style={{width: '100%'}}>
              {this.getSelectOption(model && model.deliverWay ? model.deliverWay.options : [])}
            </Select>
          </FormField>
          <FormField
            label={'原料成本合计'}
            name={'materialCost'}
            initialValue={materialCost}
          >
            <InputNumber disabled style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'采购运费合计'}
            name={'shippingFee'}
            initialValue={shippingFee}
          >
            <InputNumber disabled style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'项目奖励'}
            name={'laborFee'}
            initialValue={laborFee}
          >
            <InputNumber onChange={v => {
              this.state.laborFee = v;
              this.componentDidMount();
            }}
                         style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'奖励扣税比例%'}
            name={'laborFeeRatio'}
            initialValue={laborFeeRatio}
          >
            <InputNumber onChange={v => {
              this.state.laborFeeRatio = v;
              this.componentDidMount();
            }} style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'奖励扣税金额'}
            name={'laborFeeTax'}
            initialValue={laborFeeTax}
          >
            <InputNumber disabled style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'实际支付奖励'}
            name={'fastLaborFee'}
            initialValue={fastLaborFee}
          >
            <InputNumber disabled style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'备注'}
            name={'memo'}
            initialValue={memo}
          >
            <Input.TextArea style={{width: '100%'}}
            ></Input.TextArea>
          </FormField>
        </FormLayout>
        {warnStr && <div style={{color: '#f22'}}>{warnStr}</div>}
        <UploadPic title={"标签样式"} fileList={fileList} callback={f => this.state.fileList = f.fileList}></UploadPic>
        <ViewTitle
          title={'原料信息'}
          actions={[
            <Button type={'primary'} onClick={() => {
              ModalView.open(ModalSelectMaterial, {
                title: '选择原料',
                width: '1580px',
                maskClosable: false
              }, {
                record: {count}, isPkg: projectType === '出租',
                callback: (data) => {
                  data.usedLotId = "ULD" + new Date().valueOf();
                  materials.push(data);
                  const temp = this.state;
                  temp.materials = materials;
                  this.setState({...temp});
                }
              });
            }}>选择原料</Button>
          ]
          }
        ></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.materialTableCol()}
          dataSource={materials}
          scroll={{x: true}}
          pagination={true}
        ></Table>
        <ViewTitle
          title={'原料库存批次信息'}></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.materialLotTableCol()}
          dataSource={materialLots}
          scroll={{x: true}}
          pagination={true}
        ></Table>
        <ViewTitle
          title={'包材信息'}
          actions={[
            <Button type={'primary'} onClick={() => {
              // this.onCreateOrEditPkg();
              ModalView.open(ModalSelectMaterial, {
                title: '选择包材原料',
                width: '1580px',
                maskClosable: false
              }, {
                record: {}, isPkg: true,
                callback: (data) => {
                  data.usedLotId = "ULD" + new Date().valueOf();
                  pkgMaterials.push(data);
                  const temp = this.state;
                  temp.pkgMaterials = pkgMaterials;
                  this.setState({...temp});
                }
              });
            }}>选择包材原料</Button>
          ]
          }
        ></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.pkgCols()}
          dataSource={pkgMaterials}
          scroll={{x: true}}
          pagination={true}
        ></Table>
        <ViewTitle
          title={'包材库存批次信息'}></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.pkgLotCols()}
          dataSource={pkgLots}
          scroll={{x: true}}
          pagination={true}
        ></Table>

        <div style={{marginLeft: '64px'}}>

          <Modal visible={previewVisible} footer={null} onCancel={this.picHandleCancel}>
            <img alt="example" style={{width: '100%'}} src={previewImage}/>
          </Modal>
        </div>

        {
          this.renderFoot()
        }
      </div>

    );
  }
}

